package com.meida.module.bus.provider.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.DateUtils;
import com.meida.common.utils.FlymeUtils;
import com.meida.module.admin.client.entity.BaseUser;
import com.meida.module.bus.client.entity.*;
import com.meida.module.bus.provider.api.service.SyncOAService;
import com.meida.module.bus.provider.api.service.SyncSrmService;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsApiUtil;
import com.meida.module.bus.provider.api.util.PmsToolUtil;
import com.meida.module.bus.provider.mapper.BusReportMapper;
import com.meida.module.bus.provider.service.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

/**
 * 月报接口实现类
 *
 * @author flyme
 * @date 2020-11-02
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusReportServiceImpl extends BaseServiceImpl<BusReportMapper, BusReport> implements BusReportService {

    @Autowired
    private BusVersionService busVersionService;
    @Autowired
    private BusProjectSupplierService busProjectSupplierService;
    @Autowired
    private BusMaterialPackage100Service busMaterialPackage100Service;
    @Autowired
    private BusMaterialPackage200Service busMaterialPackage200Service;
    @Autowired
    private BusMaterialService busMaterialService;
    @Autowired
    private SyncSrmService syncSrmService;
    @Autowired
    private BusProjectService busProjectService;
    @Autowired
    private SyncOAService syncOAService;
    @Autowired
    private BusMaterialSrmSubService busMaterialSrmSubService;
    @Autowired
    private PmsApiUtil pmsApiUtil;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusReport report, EntityMap extra) {
        EntityMap requestMap = cs.getRequestMap();
        Long projectId = cs.getLong("projectId");
        BusProject busProject = busProjectService.getById(projectId);
        if (FlymeUtils.isEmpty(busProject)) {
            return ResultBody.failed("项目信息不存在");
        }
        Integer state = FlymeUtils.getInteger(busProject.getState(), 0);
        if (state == 1) {
            return ResultBody.failed("项目已锁定");
        }
        String majorCode = cs.getParams("majorCode");
        String packageNo = cs.getParams("packageNo");
        Long supplierId = cs.getLong("supplierId");
        Long materialId = cs.getLong("materialId");
        Map<String, Object> map = new HashMap<>();
        map.put("projectId", projectId);
        map.put("majorCode", majorCode);
        map.put("packageNo", packageNo);
        Long userId = OpenHelper.getUserId();
        report.setUserId(userId);
        Long versionId = requestMap.getLong("versionId");
        BusVersion busVersion = busVersionService.getById(versionId);
        Integer bigVersion = FlymeUtils.getInteger(busVersion.getBigVersion(), 0);
        report.setVer(String.valueOf(bigVersion));
        EntityMap busMaterialPackageMap = null;
        int version = bigVersion / 100;
        if (version == 1) {
            report.setReportType(1);
            busMaterialPackageMap = busMaterialPackage100Service.findById(materialId);
        }
        if (version == 2) {
            report.setReportType(2);
            busMaterialPackageMap = busMaterialPackage200Service.findById(materialId);
        }
        List<EntityMap> supplierIdList = busProjectSupplierService.getBusProjectSupplierIds(map);
        BigDecimal total = BigDecimal.ZERO;
        for (int i = 0; i < supplierIdList.size(); i++) {
            EntityMap idInfo = supplierIdList.get(i);
            Long id = idInfo.getLong("supplierId");
            if (id.longValue() == supplierId.longValue()) {
                int num = idInfo.getInt("index");
                String supplierNumId = "supplierNum" + num;
                total = busMaterialPackageMap.getBigDecimal(supplierNumId);
                break;
            }
        }
        EntityMap sumHaveReport = sumHaveReportSupplierNum(projectId, majorCode, packageNo, supplierId, materialId);
        BigDecimal totalDeclareQuantity = sumHaveReport.getBigDecimal("totalDeclareQuantity");
        BigDecimal rest = total.subtract(totalDeclareQuantity);
        BigDecimal declareQuantity = report.getDeclareQuantity();
        if (rest.compareTo(declareQuantity) == -1) {
            return ResultBody.failed("超出可申报的合同量");
        }
        report.setSyncSrm(ApiConstants.REPORT_SYNC_SRM_OFF);
        // 该处处理转为统一画面调用
        /*
        String userName = OpenHelper.getUserName();
        List<BusReport> busReportList = Lists.newArrayList();
        busReportList.add(report);
        int approvalResult = syncOAService.approval(busReportList, "/approvl/reportDetail", userName, ApiConstants.ENGINEER_APPROVAL_FB_REQ, projectId.toString());
        if (ApiConstants.APPROVAL_SUCCESS == approvalResult) {
            return ResultBody.ok("对内月报OA审批提交成功");
        } else {
            return ResultBody.failed("对内月报OA审批提交失败");
        }
        */
        return ResultBody.ok("对内月报OA提交成功");
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusReport> cq, BusReport report, EntityMap requestMap) {
        cq.addSelect(BusProject.class, "projectCode", "projectName");
        cq.addSelect(BusSupplier.class, "supplierName");
        cq.addSelect(BaseUser.class, "userName", "nickName");
        cq.addSelect(BusReport.class, "*");
        cq.eq("report.materialId", requestMap.get("materialId"));
        cq.eq("report.reportMonth", requestMap.get("reportMonth"));
        cq.eq("report.projectId", requestMap.get("projectId"));
        cq.eq("project.projectCode", requestMap.get("projectCode"));
        cq.eq("report.packageNo", requestMap.get("packageNo"));
        cq.eq("report.majorCode", requestMap.get("majorCode"));
        cq.eq("report.supplierId", requestMap.get("supplierId"));
        cq.createJoin(BusProject.class).setJoinField("projectId").setMainField("projectId");
        cq.createJoin(BusMaterial.class).setJoinField("materialId").setMainField("materialId");
        cq.createJoin(BusSupplier.class).setJoinField("supplierId").setMainField("supplierId");
        cq.createJoin(BaseUser.class).setJoinField("userId").setMainField("userId");
        cq.orderByDesc("report.createTime");
        return ResultBody.ok();
    }

    @Override
    public EntityMap sumAsOfLMonthSupplierNum(Long projectId, String majorCode, String packageNo, Long supplierId) {
        CriteriaQuery<BusReport> cq = new CriteriaQuery(BusReport.class);
        cq.addSelect("COALESCE(SUM(declareQuantity),0) totalDeclareQuantity", "COALESCE(SUM(confirmQuantity),0) totalConfirmQuantity");
        cq.eq("supplierId", supplierId);
        cq.eq("projectId", projectId);
        cq.eq("majorCode", majorCode);
        cq.eq("packageNo", packageNo);
        cq.ge("reportMonth", DateUtils.format(DateUtils.minusMonths(1), DateUtils.yyyyMM));
        return findOne(cq);
    }

    @Override
    public EntityMap sumHaveReportSupplierNum(Long projectId, String majorCode, String packageNo, Long supplierId, Long materialId) {
        CriteriaQuery<BusReport> cq = new CriteriaQuery(BusReport.class);
        cq.addSelect("COALESCE(SUM(declareQuantity),0) totalDeclareQuantity", "COALESCE(SUM(confirmQuantity),0) totalConfirmQuantity");
        cq.eq("projectId", projectId);
        cq.eq("supplierId", supplierId);
        cq.eq("majorCode", majorCode);
        cq.eq("packageNo", packageNo);
        cq.eq("materialId", materialId);
        return findOne(cq);
    }

    @Override
    public EntityMap sumHaveReportAllSupplierNum(EntityMap params, String month, List<Long> busProjectSupplierIds) {
        CriteriaQuery<BusReport> cq = new CriteriaQuery(BusReport.class);
        cq.addSelect("COALESCE(SUM(declareQuantity),0) totalDeclareQuantity", "COALESCE(SUM(confirmQuantity),0) totalConfirmQuantity");
        cq.eq("projectId", params.get("projectId"));
        cq.eq("majorCode", params.get("majorCode"));
        cq.eq("packageNo", params.get("packageNo"));
        cq.eq("materialId", params.get("materialId"));
        cq.eq("reportMonth", month);
        cq.in("supplierId", busProjectSupplierIds);
        return findOne(cq);
    }

    @Override
    public EntityMap sumHaveReportAllSupplierNumAsOfMonth(EntityMap params, String month, List<Long> busProjectSupplierIds) {
        CriteriaQuery<BusReport> cq = new CriteriaQuery(BusReport.class);
        cq.addSelect("COALESCE(SUM(declareQuantity),0) totalDeclareQuantity", "COALESCE(SUM(confirmQuantity),0) totalConfirmQuantity");
        cq.eq("materialId", params.get("materialId"));
        cq.eq("projectId", params.get("projectId"));
        cq.eq("majorCode", params.get("majorCode"));
        cq.eq("packageNo", params.get("packageNo"));
        cq.le("reportMonth", month);
        cq.in("supplierId", busProjectSupplierIds);
        return findOne(cq);
    }

    @Override
    public String getMaxReportMonth(EntityMap params) {
        CriteriaQuery<BusReport> cq = new CriteriaQuery(BusReport.class);
        cq.select("max(reportMonth) maxReportMonth");
        cq.eq("projectId", params.get("projectId"));
        cq.eq("majorCode", params.get("majorCode"));
        cq.eq("packageNo", params.get("packageNo"));
        return getObj(cq, e -> e.toString());
    }

    @Override
    public List<BusReport> selectBusReportList(Map params) {
        CriteriaQuery<BusReport> cq = new CriteriaQuery(BusReport.class);
        cq.select("*");
        cq.eq("materialId", params.get("materialId"));
        cq.eq("projectId", params.get("projectId"));
        cq.eq("majorCode", params.get("majorCode"));
        cq.eq("packageNo", params.get("packageNo"));
        return list(cq);
    }

    @Override
    public List<BusReport> selectBusReportListData(List<Long> materialIdList) {
        if (materialIdList.size() <= 0) {
            return new ArrayList<>();
        }
        CriteriaQuery<BusReport> cq = new CriteriaQuery(BusReport.class);
        cq.select("*");
        cq.in("materialId", materialIdList);
        return list(cq);
    }

    @Override
    public ResultBody importBusReport(MultipartFile file, Map params) throws Exception {
        try {
            String userName = OpenHelper.getUserName();
            Long projectId = TypeUtils.castToLong(params.get("projectId"));
            BusProject busProject = busProjectService.getById(projectId);
            if (FlymeUtils.isEmpty(busProject)) {
                return ResultBody.failed("项目信息不存在");
            }
            Integer state = FlymeUtils.getInteger(busProject.getState(), 0);
            if (state == 1) {
                return ResultBody.failed("项目已锁定");
            }
            String majorCode = (String) params.get("majorCode");
            String packageNo = (String) params.get("packageNo");
            Long supplierId = TypeUtils.castToLong(params.get("supplierId"));
            Long userId = OpenHelper.getUserId();
            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(1);
            List<Map<Object, Object>> ExcelList = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, importParams);
            for (Map<Object, Object> objectMap : ExcelList) {
                Long materialId = TypeUtils.castToLong(objectMap.get("分包Id"));
                Long versionId = TypeUtils.castToLong(objectMap.get("版本Id"));
                BigDecimal declareQuantity = TypeUtils.castToBigDecimal(objectMap.get("申报数量"));
                BigDecimal confirmQuantity = TypeUtils.castToBigDecimal(objectMap.get("确认数量"));
                String reportMonth = TypeUtils.castToString(objectMap.get("填报月份"));
                BusVersion busVersion = busVersionService.getById(versionId);
                Integer bigVersion = FlymeUtils.getInteger(busVersion.getBigVersion(), 0);
                Integer reportType = 1;
                int version = bigVersion / 100;
                if (version == 1) {
                    reportType = 1;
                }
                if (version == 2) {
                    reportType = 2;
                }
                BusReport busReport = new BusReport();
                busReport.setMaterialId(materialId);
                busReport.setSupplierId(supplierId);
                busReport.setProjectId(projectId);
                busReport.setMajorCode(majorCode);
                busReport.setPackageNo(packageNo);
                busReport.setReportType(reportType);
                busReport.setDeclareQuantity(declareQuantity);
                busReport.setConfirmQuantity(confirmQuantity);
                busReport.setReportMonth(reportMonth);
                busReport.setUserId(userId);
                busReport.setCreateTime(DateUtils.getNowDateTime());
                busReport.setVer(String.valueOf(bigVersion));
                busReport.setSyncSrm(ApiConstants.REPORT_SYNC_SRM_OFF);
                boolean save = save(busReport);
                // 该处处理转为统一画面调用
                /*
                if (save) {
                    EntityMap entityMap = new EntityMap();
                    params.put("materialId", busReport.getMaterialId());
                    entityMap.putAll(params);
                    entityMap.put("reportMonth", reportMonth);
                    //进行计算代码
                    //saveBusReportAfter(entityMap, reportType);
                    syncOAService.approval(params, "/approvl/reportDetail", userName, ApiConstants.ENGINEER_APPROVAL_FB_REQ, projectId.toString());
                }
                */
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return ResultBody.ok("导入成功");
    }

    /**
     * oa审批通过后.调取该方法
     *
     * @param params     需要参数materialId,reportMonth,projectId,majorCode,packageNo,
     * @param reportType 100的还是200的
     */
    @SneakyThrows
    @Override
    public void saveBusReportAfter(EntityMap params, Integer reportType) {
        String maxReportMonth = getMaxReportMonth(params);
        Long materialId = params.getLong("materialId");
        String reportMonth = params.get("reportMonth");
        if (FlymeUtils.isEmpty(maxReportMonth)) {
            maxReportMonth = reportMonth;
        }
        List<EntityMap> busProjectSupplierIdList = busProjectSupplierService.getBusProjectSupplierIds(params);
        List<Long> busProjectSupplierIds = new ArrayList<>();
        for (EntityMap entityMap : busProjectSupplierIdList) {
            Long supplierId = entityMap.getLong("supplierId");
            busProjectSupplierIds.add(supplierId);
        }
        //完成工程量_本月完成工程量/本月确认工程量
        BigDecimal currentFinishMonthCount = BigDecimal.ZERO;
        //完成工程量_截止上月完成工程量
        BigDecimal lastFinishMonthCount = BigDecimal.ZERO;
        BigDecimal totalFinishCount = BigDecimal.ZERO;
        if (busProjectSupplierIds.size() > 0) {
            EntityMap currentFinishEntityMap = sumHaveReportAllSupplierNum(params, maxReportMonth, busProjectSupplierIds);
            currentFinishMonthCount = currentFinishEntityMap.getBigDecimal("totalConfirmQuantity");
            LocalDate lastMonthDate = LocalDate.parse(maxReportMonth + "-01");
            String lastMonth = DateUtils.format(lastMonthDate.minusMonths(1), DateUtils.yyyyMM);
            EntityMap lastMonthFinishEntityMap = sumHaveReportAllSupplierNumAsOfMonth(params, lastMonth, busProjectSupplierIds);
            lastFinishMonthCount = lastMonthFinishEntityMap.getBigDecimal("totalConfirmQuantity");
            EntityMap allMonthFinishEntityMap = sumHaveReportAllSupplierNumAsOfMonth(params, maxReportMonth, busProjectSupplierIds);
            totalFinishCount = allMonthFinishEntityMap.getBigDecimal("totalConfirmQuantity");
        }
        BusMaterial busMaterial = busMaterialService.getById(materialId);
        busMaterial.setCurrentFinishMonthCount(currentFinishMonthCount);
        busMaterial.setLastFinishMonthCount(lastFinishMonthCount);
        busMaterial.setTotalFinishCount(totalFinishCount);
        BigDecimal mainPrice3 = FlymeUtils.getBigDecimal(busMaterial.getMainPrice3(), "0");
        BigDecimal installPrice3 = FlymeUtils.getBigDecimal(busMaterial.getInstallPrice3(), "0");
        //本月实现产值未税_合同价_合价_主材价
        BigDecimal currentMonthmainPrice = currentFinishMonthCount.multiply(mainPrice3).setScale(5);
        busMaterial.setCurrentMonthmainPrice(currentMonthmainPrice);
        //本月实现产值未税_合同价_合价_安装价
        BigDecimal currentMonthinstallPrice = currentFinishMonthCount.multiply(installPrice3).setScale(5);
        busMaterial.setCurrentMonthinstallPrice(currentMonthinstallPrice);
        //本月实现产值未税_合同价_合价_合计
        BigDecimal currentMonthsumPrice = currentMonthmainPrice.add(currentMonthinstallPrice).setScale(5);
        busMaterial.setCurrentMonthsumPrice(currentMonthsumPrice);
        //截止上月实现产值未税_合同价_合价_主材价
        BigDecimal lastMonthmainPrice = lastFinishMonthCount.multiply(mainPrice3).setScale(5);
        busMaterial.setLastMonthmainPrice(lastMonthmainPrice);
        //截止上月实现产值未税_合同价_合价_安装价
        BigDecimal lastMonthinstallPrice = lastFinishMonthCount.multiply(installPrice3).setScale(5);
        busMaterial.setLastMonthinstallPrice(lastMonthinstallPrice);
        //本月实现产值未税_合同价_合价_合计
        BigDecimal lastMonthsumPrice = lastMonthmainPrice.add(lastMonthinstallPrice).setScale(5);
        busMaterial.setLastMonthsumPrice(lastMonthsumPrice);
        //累计实现产值未税_合同价_合价_主材价
        BigDecimal totalMonthmainPrice = totalFinishCount.multiply(mainPrice3).setScale(5);
        busMaterial.setTotalMonthmainPrice(totalMonthmainPrice);
        //累计实现产值未税_合同价_合价_安装价
        BigDecimal totalMonthinstallPrice = totalFinishCount.multiply(installPrice3).setScale(5);
        busMaterial.setTotalMonthinstallPrice(totalMonthinstallPrice);
        //累计实现产值未税_合同价_合价_合计
        BigDecimal totalsumPrice = totalMonthmainPrice.add(totalMonthinstallPrice).setScale(5);
        busMaterial.setTotalsumPrice(totalsumPrice);
        busMaterialService.updateById(busMaterial);
        List<Long> materialIdList = Lists.newArrayList();
        materialIdList.add(materialId);
        List<BusReport> busReportList= selectBusReportListData(materialIdList);
        // TODO: 修改位置
//        if (reportType == 1) {
//            syncSrmService.busReportServiceImpl(busReportList, ApiConstants.VER_100);
//        }
//        if (reportType == 2) {
//            syncSrmService.busReportServiceImpl(busReportList, ApiConstants.VER_200);
//        }
    }

    @Override
    public ResultBody getPreViewData(Map params) {
        // params={"projectId":"2022","packageNo":"P01J1","majorCode":"P01","materialId":"1366572118279512066","versionId":"1366572116840865794","isGroup":false,"isReport":true}, NONCE=go4pddrpdr5
        JSONObject filterObj = JSONUtil.parseObj(params.get("params"));
        BusVersion busVersion = busVersionService.getById(filterObj.getLong("versionId"));
        CriteriaQuery<BusReport> cq = new CriteriaQuery(BusReport.class);
        cq.createJoin(BusMasterAlldataView.class).setJoinField("materialId").setMainField("materialId");
        cq.createJoin(BusSupplier.class).setJoinField("supplierId").setMainField("supplierId");
//        if(String.valueOf(ApiConstants.VER_100).equals(busVersion.getBigVersion())) {
//            cq.createJoin(BusMaterialPackage100.class).setJoinField("materialId").setMainField("materialId");
//            cq.addSelect(BusMaterialPackage100.class, "*");
//        } else {
//            cq.createJoin(BusMaterialPackage200.class).setJoinField("materialId").setMainField("materialId");
//            cq.addSelect(BusMaterialPackage200.class, "*");
//        }

        cq.addSelect(BusReport.class, "*");
        cq.addSelect(BusMasterAlldataView.class, "*");
        cq.addSelect(BusSupplier.class, "*");


        cq.eq("report.projectId", filterObj.getStr("projectId"));
        cq.eq("report.packageNo", filterObj.getStr("packageNo"));
        cq.eq("report.syncSrm", ApiConstants.REPORT_SYNC_SRM_OFF);
        cq.ne("report.auditState", ApiConstants.APPROVAL_FAIL);//审批状态不为驳回

        cq.orderByDesc("report.createTime");
        Map<String, Object> searchMap = Maps.newHashMap();
        searchMap.put("projectId", filterObj.getStr("projectId"));
        searchMap.put("packageNo", filterObj.getStr("packageNo"));
        //获取分包供应商信息
        BusProjectSupplier busProjectSupplier = busProjectSupplierService.listByMap(searchMap).stream().findFirst().get();

        List<EntityMap> entityMapList = selectEntityMap(cq);
        entityMapList.stream().forEach(entity -> {
            for (int i = 1; i < 11; i++) {
                if (entity.getLong("supplierId").equals(PmsToolUtil.getLongValue(busProjectSupplier, ApiConstants.INVOKE_GET_SUPPLIERID + i))) {
                    Object packageData = null;
                    if (String.valueOf(ApiConstants.VER_100).equals(busVersion.getBigVersion())) {
                        packageData = busMaterialPackage100Service.getById(entity.getLong("materialId"));
                    } else {
                        packageData = busMaterialPackage200Service.getById(entity.getLong("materialId"));
                    }
                    entity.put("supplierSum", PmsToolUtil.getBigDecimalValue(packageData, ApiConstants.INVOKE_GET_SUPPLIERNUM + i));
//                        BusMaterial busMaterial = busMaterialService.getById(entity.getLong("materialId"));

                }
            }
        });
        return ResultBody.ok(entityMapList);
    }

    @Override
    public ResultBody syncData(Map params) throws Exception {
        //参数示例
//        dataArray: [{"auditState":0,"beforeMarkQuantity":1,"brandName":"","confirmQuantity":0,"contractBillQuantity":0,"contractDesc":"","contractsumSyntheticalPrice1":0,"contractsumSyntheticalPrice2":0,"contractsumSyntheticalPrice3":0,"costQuantity100":1,"costQuantity200":1,"createTime":"2021-05-14 16:05:45","currentFinishMonthCount":"","currentMonthinstallPrice":0,"currentMonthmainPrice":0,"currentMonthsumPrice":0,"dataKind":"0","declareQuantity":0,"installAmount":700000,"installAmount1":0,"installAmount2":0,"installAmount3":0,"installPrice":700000,"installPrice1":0,"installPrice2":0,"installPrice3":0,"installsumPrice1":0,"installsumPrice2":0,"installsumPrice3":0,"instructNumber":"","lastFinishMonthCount":"","lastMonthinstallPrice":0,"lastMonthmainPrice":0,"lastMonthsumPrice":0,"levelNo":"F02A1000100","loss":"","mainAmount":0,"mainAmount1":0,"mainAmount2":0,"mainAmount3":0,"mainPrice":0,"mainPrice1":0,"mainPrice2":0,"mainPrice3":0,"mainsumPrice1":0,"mainsumPrice2":0,"mainsumPrice3":0,"majorCode":"F02","majorName":"吊装费","materiaSpecs":"","materialArea":"","materialCode":"","materialDesc":"","materialId":"1392390277385224194","materialName":"","materialUse":"","materialWbsCode":"","measurementUnit":"式","packageDesc":"","packageName":"吊装费","packageNo":"F02A1","packagePlanId":"1392390277385224194","planType":"","projectCode":"TEST0511003","projectId":"110","projectName":"新北方广播大厦改扩建test","remark":"","reportId":"1393115301859651585","reportMonth":"2021-05-14","reportType":2,"serviceCode":"FE010001","serviceWbsCode":"B0360HFJH01F02A1","subjectName":"","supplierCode":"S200024","supplierId":"1379965624368799745","supplierName":"飞机电设备安装工程有限公司","supplierSum":0,"syncFlg":"","syncSrm":"0","syntheticalAmount":700000,"syntheticalAmount1":0,"syntheticalAmount2":0,"syntheticalAmount3":0,"syntheticalPrice":700000,"syntheticalPrice1":0,"syntheticalPrice2":0,"syntheticalPrice3":0,"technicalData":"","totalFinishCount":"","totalMonthinstallPrice":0,"totalMonthmainPrice":0,"totalsumPrice":0,"type":"200分包","unitBillQuantity100":"","unitBillQuantity200":"","updateTime":"","userId":"1345927323395895297","ver":"200"}]
//        params: {"projectId":"110","packageNo":"F02A1","majorCode":"F02","materialId":"1392390277385224194","versionId":"1392390273903951874","isGroup":false,"isReport":true}
        JSONObject filterObj = JSONUtil.parseObj(params.get("params"));
        List<EntityMap> listentityMap = JSON.parseArray(String.valueOf(params.get("dataArray")), EntityMap.class);

        // 未签署合同
        ResultBody resultBodyCk = pmsApiUtil.ckRerport(listentityMap);
        if(!resultBodyCk.isOk()) {
            return resultBodyCk;
        }

        List<BusReport> busReports = Lists.newArrayList();
        List<Long> reportIds = Lists.newArrayList();
        if (0 < listentityMap.size()) {
            listentityMap.stream().forEach(obj -> {
                reportIds.add(obj.getLong("reportId"));
                BusReport updReport = new BusReport();
                updReport.setReportId(obj.getLong("reportId"));
                String reportMonth = (String) obj.get("reportMonth");
                updReport.setReportMonth(reportMonth.substring(0, 7));
                //申报数量
                updReport.setDeclareQuantity(obj.getBigDecimal("declareQuantity"));
                //确认数量
                updReport.setConfirmQuantity(obj.getBigDecimal("confirmQuantity"));
                updReport.setSyncSrm(ApiConstants.REPORT_SYNC_SRM_ON);
                updReport.setAuditState(ApiConstants.APPROVAL_ING);//审批状态为审批中
                busReports.add(updReport);
                System.out.println(obj.toString());
            });
            if (0 < busReports.size()) {
                updateBatchById(busReports);
                BusVersion busVersion = busVersionService.getById(filterObj.getLong("versionId"));
                List<BusReport> busReportApprovals = (List<BusReport>) listByIds(reportIds);
                Map<String, Object> approvalMap = Maps.newHashMap();
                approvalMap.put(ApiConstants.REDIS_KEY_BUSREPORT_APPROVALS, busReportApprovals);
                approvalMap.put(ApiConstants.REDIS_KEY_BUSREPORT_VER, busVersion.getBigVersion());

                int approvalResult = syncOAService.approval(approvalMap, "/approvl/reportDetail",
                    OpenHelper.getUserName(), ApiConstants.ENGINEER_APPROVAL_FB_REQ, String.valueOf(busVersion.getProjectId()));
                if (ApiConstants.APPROVAL_SUCCESS == approvalResult) {
                    return ResultBody.ok("对内月报OA审批提交成功");
                } else {
                    return ResultBody.failed("对内月报OA审批提交失败");
                }

                // return syncSrmService.busReportServiceImpl(busReportsOut, Integer.valueOf(busVersion.getBigVersion()));
            }
        }

        return ResultBody.ok();
    }

    /**
     * 修改记录的审核状态
     * @param state
     * @param reports
     * @return
     */
    @Override
    public void mergeAuditState(int state, List<BusReport> reports) {
        if(!CollectionUtils.isEmpty(reports)) {
            List<Long> ids = Lists.newArrayList();
            reports.forEach(item -> {
                ids.add(item.getReportId());
            });
            CriteriaUpdate<BusReport> cu = new CriteriaUpdate();
            cu.in("reportId", ids);
            cu.set("auditState", state);
            update(cu);
        }
    }
}
